<template>
  <div class="app-container">
    <!-- 主容器 -->
    <el-row :gutter="20">
      <!-- 左侧模板列表 -->
      <el-col :span="6">
        <el-card>
          <div class="list-header">
            <el-button type="primary" @click="showAddTemplateDialog" icon="Plus">新建</el-button>
          </div>
          <!-- 模板列表 -->
          <Scrollbar :activeTemplate="activeTemplate" :templateList="templateList" @selectTemplate="selectTemplate" @showEditTemplateDialog="showEditTemplateDialog" @deleteTemplate="deleteTemplate"/>
        </el-card>
      </el-col>

      <!-- 右侧指标详情 -->
      <el-col :span="18">
        <el-card>
          <div class="detail-header">
            <div>
              <h3>{{ activeTemplate.templateName }}</h3>
              <p>{{ activeTemplate.templateDescription }}</p>
            </div>
            <div class="detail-actions">
              <el-button @click="exportTemplate">导出</el-button>
              <el-button @click="openImportDialog">导入</el-button>
              <el-button type="primary" @click="showAddIndicatorDialog" icon="Plus">添加指标</el-button>
            </div>
          </div>

          <!-- 指标表格 -->
          <el-table :data="activeTemplate.indicators" border class="mt-2" v-loading="loading"
            :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
            <el-table-column prop="waterQualityIndex" label="指标名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column label="标准值">
              <template #default="{ row }">
                {{ row.standardMin }} - {{ row.standardMax }}
              </template>
            </el-table-column>
            <el-table-column prop="isMandatory" label="是否必填">
              <template #default="{ row }">
                <el-tag :type="row.isMandatory === 1 ? 'success' : 'info'">
                  {{ row.isMandatory === 1 ? '必填' : '非必填' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="displayOrder" label="展示顺序" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="showEditIndicatorDialog(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteIndicator(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增模板对话框 -->
    <el-dialog v-model="addTemplateDialogVisible" title="新增水质指标模板" width="50%" :close-on-click-modal="false">
      <el-form :model="addTemplateForm" label-width="120px" :rules="templateRules" ref="addTemplateFormRef">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="addTemplateForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="templateDescription">
          <el-input v-model="addTemplateForm.templateDescription" type="textarea" :rows="2" placeholder="请输入模板描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTemplateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑模板对话框 -->
    <el-dialog v-model="editTemplateDialogVisible" title="编辑水质指标模板" width="50%" :close-on-click-modal="false">
      <el-form :model="editTemplateForm" label-width="120px" :rules="templateRules" ref="editTemplateFormRef">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="editTemplateForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="templateDescription">
          <el-input v-model="editTemplateForm.templateDescription" type="textarea" :rows="2" placeholder="请输入模板描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editTemplateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑指标对话框 -->
    <el-dialog v-model="indicatorDialogVisible" :title="indicatorDialogTitle" width="60%" :close-on-click-modal="false">
      <el-form :model="currentIndicator" label-width="120px" :rules="indicatorRules" ref="indicatorFormRef">
        <el-form-item label="指标名称" prop="waterQualityIndex">
          <el-select v-model="currentIndicator.waterQualityIndex" placeholder="请选择水质指标" style="width: 100%"
            @change="handleIndexChange">
            <el-option v-for="item in basicIndexOptions" :key="item.waterQualityIndex" :label="item.waterQualityIndex"
              :value="item.waterQualityIndex" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="currentIndicator.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="标准最小值" prop="standardMin">
          <el-input-number v-model="currentIndicator.standardMin" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="标准最大值" prop="standardMax">
          <el-input-number v-model="currentIndicator.standardMax" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isMandatory">
          <el-switch v-model="currentIndicator.isMandatory" :active-value="1" :inactive-value="0" active-text="必填"
            inactive-text="非必填" />
        </el-form-item>
        <el-form-item label="展示顺序" prop="displayOrder">
          <el-input-number v-model="currentIndicator.displayOrder" :min="1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="indicatorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmIndicator">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入模板对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="420px" append-to-body :close-on-click-modal="false">
      <el-upload
        ref="uploadRef"
        drag
        :limit="1"
        accept=".xlsx,.xls"
        :headers="upload.headers"
        :action="`${upload.url}?updateSupport=${upload.updateSupport}`"
        :disabled="upload.isUploading"
        :auto-upload="false"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
      >
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="mb-1">
              <el-checkbox v-model="upload.updateSupport">是否更新已存在的数据</el-checkbox>
            </div>
            <div>仅允许导入 xls、xlsx 格式文件。</div>
            <el-link type="primary" :underline="false" @click="downloadImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">上传</el-button>
          <el-button :disabled="upload.isUploading" @click="upload.open = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import Scrollbar from '@/components/Scrollbar'
import {
  getWaterQualityTemplateList,
  getWaterQualityTemplateDetail,
  addWaterQualityTemplate,
  updateWaterQualityTemplate,
  deleteWaterQualityTemplate,
  getBasicIndexList,
  getTemplateList,
  addTemplate,
  updateTemplate
} from '@/api/prod_operate/sys_setting/water/indicator_template'

const { proxy } = getCurrentInstance()

// 加载状态
const loading = ref(false)

// 模板列表数据
const templateList = ref([])

// 当前选中的模板
const activeTemplate = ref({
  templateId: '',
  templateName: '',
  templateDescription: '',
  indicators: []
})

// 基础指标选项
const basicIndexOptions = ref([])

// 新增模板表单
const addTemplateForm = reactive({
  templateName: '',
  templateDescription: ''
})

// 编辑模板表单
const editTemplateForm = reactive({
  id: '',
  templateName: '',
  templateDescription: ''
})

// 当前指标
const currentIndicator = reactive({
  templateId: '',
  waterQualityIndex: '',
  unit: '',
  standardMin: 0,
  standardMax: 0,
  isMandatory: 1,
  displayOrder: 1
})

// 对话框控制
const addTemplateDialogVisible = ref(false)
const editTemplateDialogVisible = ref(false)
const indicatorDialogVisible = ref(false)
const indicatorDialogTitle = ref('新增指标')

// 表单引用
const addTemplateFormRef = ref(null)
const editTemplateFormRef = ref(null)
const indicatorFormRef = ref(null)
const uploadRef = ref(null)

// 表单验证规则
const templateRules = reactive({
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  templateDescription: [
    { required: true, message: '请输入模板描述', trigger: 'blur' }
  ]
})

const indicatorRules = reactive({
  waterQualityIndex: [
    { required: true, message: '请选择水质指标', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  standardMin: [
    { required: true, message: '请输入标准最小值', trigger: 'blur' }
  ],
  standardMax: [
    { required: true, message: '请输入标准最大值', trigger: 'blur' }
  ],
  displayOrder: [
    { required: true, message: '请输入展示顺序', trigger: 'blur' }
  ]
})

// 导入相关
const upload = reactive({
  open: false,
  title: '导入模板',
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + '/operation/web/operationWaterQualityTemplate/importData'
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取模板列表
    const templateRes = await getWaterQualityTemplateList({})
    templateList.value = templateRes.rows

    // 获取基础指标列表
    const indexRes = await getBasicIndexList()
    basicIndexOptions.value = indexRes.data

    // 默认选中第一个模板
    if (templateList.value.length > 0) {
      await selectTemplate(templateList.value[0])
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 选择模板
const selectTemplate = async (template) => {
  try {
    loading.value = true;
    const res = await getWaterQualityTemplateDetail(template.id)
    activeTemplate.value = res.data

    const data = await getTemplateList(template);

    activeTemplate.value.indicators = data.rows;

  } catch (error) {
    console.error('获取模板详情失败:', error)
    ElMessage.error('获取模板详情失败')
  } finally {
    loading.value = false
  }
}

// 显示新增模板对话框
const showAddTemplateDialog = () => {
  addTemplateForm.templateName = ''
  addTemplateForm.templateDescription = ''
  addTemplateDialogVisible.value = true
}

// 确认新增模板
const confirmAddTemplate = async () => {
  try {
    await addTemplateFormRef.value.validate()
    console.log(addTemplateForm);

    const res = await addWaterQualityTemplate(addTemplateForm)
    ElMessage.success('新增模板成功')
    addTemplateDialogVisible.value = false

    // 刷新模板列表
    const templateRes = await getWaterQualityTemplateList({})
    templateList.value = templateRes.rows

    // 选中新创建的模板
    const newTemplate = templateList.value.find(t => t.templateId === res.data.templateId)
    if (newTemplate) {
      await selectTemplate(newTemplate)
    }
  } catch (error) {
    console.error('新增模板失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

const deleteTemplate = (template) => {
  ElMessageBox.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteWaterQualityTemplate([template.id])
    // 刷新模板列表
    const templateRes = await getWaterQualityTemplateList({})
    templateList.value = templateRes.rows

    ElMessage.success('删除成功')

  })
}

// 显示编辑模板对话框
const showEditTemplateDialog = (template) => {
  Object.assign(editTemplateForm, template);
  editTemplateDialogVisible.value = true
}

// 确认编辑模板
const confirmEditTemplate = async () => {
  try {
    await editTemplateFormRef.value.validate()

    await updateWaterQualityTemplate(editTemplateForm)


    // 刷新模板列表
    const templateRes = await getWaterQualityTemplateList({})
    templateList.value = templateRes.rows

    ElMessage.success('修改模板成功')
    editTemplateDialogVisible.value = false

  } catch (error) {
    console.error('修改模板失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 显示新增指标对话框
const showAddIndicatorDialog = () => {
  indicatorDialogTitle.value = '新增指标'
  Object.assign(currentIndicator, {
    templateId: activeTemplate.value.id,
    waterQualityIndex: '',
    unit: '',
    standardMin: 0,
    standardMax: 0,
    isMandatory: 1,
    displayOrder: activeTemplate.value.indicators.length + 1
  })
  indicatorDialogVisible.value = true
}

// 显示编辑指标对话框
const showEditIndicatorDialog = (indicator) => {
  indicatorDialogTitle.value = '编辑指标'
  Object.assign(currentIndicator, indicator)
  indicatorDialogVisible.value = true
}

// 处理指标选择变化
const handleIndexChange = (value) => {
  const selectedIndex = basicIndexOptions.value.find(item => item.waterQualityIndex === value)
  if (selectedIndex) {
    currentIndicator.unit = selectedIndex.unit
    currentIndicator.standardMin = selectedIndex.standardMin || 0
    currentIndicator.standardMax = selectedIndex.standardMax || 0
  }
}

// 确认指标操作
const confirmIndicator = async () => {
  try {
    await indicatorFormRef.value.validate()

    if (indicatorDialogTitle.value === '新增指标') {
      await addTemplate({...currentIndicator , templateName: activeTemplate.value.templateName });
    } else {
      await updateTemplate(currentIndicator);
    }
    selectTemplate(activeTemplate.value)
    ElMessage.success(`${indicatorDialogTitle.value}成功`)
    indicatorDialogVisible.value = false
  } catch (error) {
    console.error('保存指标失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除指标
const handleDeleteIndicator = (indicator) => {
  ElMessageBox.confirm('确认删除该指标吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 从当前模板中移除指标
      const index = activeTemplate.value.indicators.findIndex(
        i => i.waterQualityIndex === indicator.waterQualityIndex
      )
      if (index !== -1) {
        activeTemplate.value.indicators.splice(index, 1)
      }

      // 保存到服务器
      await updateWaterQualityTemplate(activeTemplate.value)
      ElMessage.success('删除指标成功')
    } catch (error) {
      console.error('删除指标失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 导出模板
const exportTemplate = () => {
  if (!activeTemplate.value || !activeTemplate.value.templateName) {
    ElMessage.warning('请选择需要导出的模板')
    return
  }
  const params = {
    templateName: activeTemplate.value.templateName
  }
  proxy?.download(
    '/operation/web/operationWaterQualityTemplate/export',
    params,
    `water_quality_template_${Date.now()}.xlsx`
  )
}

// 打开导入对话框
const openImportDialog = () => {
  upload.title = '导入水质指标模板'
  upload.open = true
  upload.isUploading = false
}

// 下载导入模板
const downloadImportTemplate = () => {
  proxy?.download(
    '/operation/web/operationWaterQualityTemplate/importTemplate',
    {},
    `water_quality_template_import_${Date.now()}.xlsx`
  )
}

// 上传进度
const handleFileUploadProgress = () => {
  upload.isUploading = true
}

// 上传成功
const handleFileSuccess = async (response) => {
  upload.isUploading = false
  upload.open = false
  uploadRef.value?.clearFiles()
  ElMessageBox.alert(
    `<div style="max-height: 60vh;overflow:auto;padding:10px 0;">${response.msg}</div>`,
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  await initData()
}

// 提交上传
const submitFileForm = () => {
  if (!uploadRef.value) return
  uploadRef.value.submit()
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}



.template-desc {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.template-count {
  font-size: 12px;
  color: #409eff;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
}

.detail-header p {
  margin: 5px 0 0;
  color: #909399;
  font-size: 14px;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-select {
  width: 100%;
}

.el-input-number {
  width: 100%;
}
</style>